#!/bin/bash
#
#--------------------------------------------
# 功能：
# 作者：
# 创建日期：
#--------------------------------------------
SPACE="=============="
#Config Color
RED="${SPACE}\033[0;31m"
GREEN="${SPACE}\033[0;32m"
NC="\033[0m" # No Color

#上传服务器配置
appId="1562830544"
versionId="1.0.1"
uploadUrl="http://*********/test/upload.json"

#证书及描述文件
#开发环境：Apple Development: bai hao (PB5RVURJ6L)、描述文件：zdscDev
#生产环境：Apple Distribution: bai hao (CUKDG3HAM3)、描述文件：zdscAppStore
CODE_SIGN_IDENTITY="Apple Distribution: bai hao (CUKDG3HAM3)"
DEVELOPMENT_TEAM="CUKDG3HAM3"
PROVISIONING_PROFILE_SPECIFIER="zdscAppStore"

echo "Place enter the number you want to export ? [ 1:app-store 2:ad-hoc] "
##
read number
while([[ $number != 1 ]] && [[ $number != 2 ]])
do
echo "Error! Should enter 1 or 2"
echo "Place enter the number you want to export ? [ 1:app-store 2:ad-hoc] "
read number
done

if [ $number == 1 ];then
    build_env=prd
else
    build_env=Pre
fi
echo "${RED}==${build_env}"

#工程路径读取
workspace_path="$(cd "$(dirname $0)" && pwd)"
echo -e "${GREEN}路径:${workspace_path}${NC}"
cd ${workspace_path}
workspace_name=$(ls | grep xcworkspace)
echo -e "${GREEN}工程名称:${workspace_name}${NC}"
project_path=${workspace_path}
echo -e "${GREEN}project_path:${project_path}${NC}"
project_name=$(ls ${workspace_path} | grep xcodeproj | awk -F.xcodeproj '{print $1}')
echo -e "${GREEN}project_name:${project_name}${NC}"
target_name=${project_name}
echo -e "${GREEN}target_name:${target_name}${NC}"
info_plist=${project_path}/${project_name}/Info.plist
result_path=${workspace_path}/build/${build_env}_$(date +%Y-%m-%d_%H_%M)

#工程代码更新
echo "======开始更新代码======"
#cd ${project_path}
#git stash
#git pull --rebase
#cd ${workspace_path}
#pod update --no-repo-update --verbose
#if [ $? != 0 ]; then
#    echo "======代码更新失败======"
#    exit 1
#else
#    echo "======完成代码更新======"
#fi

#修改版本号
if [ -n "$2" ]; then
    bundleShortVersion=$(echo $2 | perl -pe 's/.*/\u$&/')
    /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${bundleShortVersion}" ${info_plist}
else
    #主版本号读取
    bundleShortVersion=$(/usr/libexec/PlistBuddy -c "print CFBundleShortVersionString" ${info_plist})
fi


#应用标识及名称修改
case "$1" in
    sit|pre|pre2|pre3)
        bundle_identifier=com.suning.${build_env}
        bundle_name=${build_env}${bundleShortVersion}
        echo -e "${RED}配置走dddd的这儿:${build_env}${NC}"
        ;;
    Sit|Pre|Pre2|Pre3|Prd|prd)
        bundle_identifier=com.suning.SuningEfubao
        bundle_name="****test"
        echo -e "${RED}配置走ddass这儿:${build_env}${NC}"
    ;;
    *)
    #如果都不是，则执行此程序
    bundle_name=${project_name}
    bundle_identifier=com.suning.${build_env}
    echo "Your choose is error!${bundle_name}"
    ;;
esac

/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier ${bundle_identifier}" ${info_plist}
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName ${bundle_name}" ${info_plist}

#Today Extension
te_info_plist=${project_path}/${project_name}/Info.plist
if [ -f ${nse_info_plist} ]; then
    te_bundle_identifier=${bundle_identifier}.NSExtension
    /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier ${te_bundle_identifier}" ${te_info_plist}
fi

#Notification Service Extension
nse_info_plist=${project_path}/NotificationServiceExtension/Info.plist
if [ -f ${nse_info_plist} ]; then
    nse_bundle_identifier=${bundle_identifier}.NotificationServiceExtension
    /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier ${nse_bundle_identifier}" ${nse_info_plist}
fi

#打包环境修改
config_file=${project_path}/Project/Src/Constants/BuildConfig.h

if [ -f ${config_file} ]; then

    upper_env=$(echo ${build_env} | tr '[a-z]' '[A-Z]')

    echo "======修改环境配置======"
    sed -i '' "/TARGET_ENV_/ s/1/0/" ${config_file}
    sed -i '' "/TARGET_ENV_${upper_env}/ s/0/1/" ${config_file}

    sed -i '' "/DEBUG_ENABLE/ s/1/0/" ${config_file}

fi

#构建路径设置
mkdir -p "${result_path}"
setting_out=${result_path}/build_setting.txt
xcodebuild -showBuildSettings -workspace "${workspace_name}" -scheme "${target_name}" -configuration Release > ${setting_out}
build_path=`echo $(grep -w  "CONFIGURATION_BUILD_DIR" ${setting_out} | awk -F= '{print $2}')`
echo "======build_path: ${build_path}======"
archive_path=${build_path}/${target_name}.xcarchive


#清除旧包
rm -rf ${archive_path}
#归档打包
echo "======开始构建======"
xcodebuild clean archive -workspace "${workspace_name}" \
-scheme "${target_name}" \
-archivePath ${archive_path} \
-configuration Release \
CODE_SIGN_IDENTITY="${CODE_SIGN_IDENTITY}" \
DEVELOPMENT_TEAM="${DEVELOPMENT_TEAM}" \
PROVISIONING_PROFILE_SPECIFIER="${PROVISIONING_PROFILE_SPECIFIER}"

echo "======检查是否构建成功======"
if [ -d "${archive_path}" ]; then

    echo "构建成功......"

else

    echo -e "\033[31m 构建失败，请修正后重新运行! \033[0m"
    rm -rf ${result_path}
    exit 1

fi

cd ${project_path}
git checkout -- ${config_file}
git checkout -- ${info_plist}
git checkout -- SNYifubao.xcodeproj/project.pbxproj

ipa_name=${target_name}_${bundleShortVersion}.ipa
ipa_path=${result_path}
ExportOptionsPlist=${project_path}/ExportOptions.plist

#XCODE8 需要使用系统的ruby
which rvm > /dev/null
if [[ $? -eq 0 ]]; then
    echo "RVM detected, forcing to use system ruby"
    [ -s "$HOME/.rvm/scripts/rvm" ] && . "$HOME/.rvm/scripts/rvm"
    rvm use system
fi

#导出ipa
xcodebuild -exportArchive \
-archivePath ${archive_path} \
-exportOptionsPlist ${ExportOptionsPlist} \
-exportPath ${ipa_path}

echo "======检查是否成功导出ipa======"
ipa_temp_path=${ipa_path}/${target_name}.ipa
if [ -f "${ipa_temp_path}" ]; then
    echo "导出ipa成功......"
    #ipa重命名
    mv "${ipa_temp_path}" "${ipa_path}/${ipa_name}"
else
    echo -e "\033[31m 导出ipa失败...... \033[0m"
    exit 1
fi

#备份dSYM
dsym_path=${archive_path}/dSYMs/${target_name}.app.dSYM/Contents/Resources/DWARF/${target_name}
cp -R "${dsym_path}" "${result_path}/${target_name}.dSYM"

#info名称
ipa_info=${target_name}_${bundleShortVersion}.info
echo ${target_name} ${bundleShortVersion} $1"($(date "+%Y-%m-%d %H:%M"))" > ${result_path}/${ipa_info}
ipaDesc="****test"$1

echo "======result_path: ${result_path}======"

###########################################文件上传###########################################

echo "======开始上传测试包======"
case "$build_env" in
Pre|Pre2|Pre3)
build_env="Pre";;
esac
cd ${result_path}
#curl -T "{${ipa_name},${ipa_info}}" -u epp:ios ftp://*********/${build_env}/ipa/


curl -F "appId=${appId}" -F "versionId=${versionId}" -F "bundleId=${bundle_identifier}" -F "ipaDesc=${ipaDesc}" -F "ipaFile=@${ipa_path}/${ipa_name}" ${uploadUrl}

echo "======共耗时${SECONDS}秒======"
